﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Globalization;

namespace ReconUI
{
    public partial class MatchInvoice : System.Web.UI.Page
    {
        DataTable dtUnMatchInvoices;
        DataTable dtUnMatchStatement;
        DBFactory db;
        ReconcileService objReconcileService;
        String matchType = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (((UserVO)Session["CurrentUserVO"]) == null)
            {
                Response.Redirect("ReconSignIn.aspx");
            }
            if (!Page.IsPostBack)
            {
                // GetUnmatchedLists();
                FillRemitterForMatching();
            }
           
            //String scriptText = " $(document).ready(function () {$('#<%=grdInvoice.ClientID %>').Scrollable();}";
            //ClientScript.RegisterOnSubmitStatement(this.GetType(),
            //    "", scriptText);
           // ClientScript.RegisterOnSubmitStatement(this.GetType(), "key", "<script>ab()</script>");
          //  ClientScript.RegisterOnSubmitStatement(this.GetType(), "key", "<script>MakeStaticHeader('" + GridView1.ClientID + "', 400, 950 , 40 ,true); </script>");
          //  ScriptManager.RegisterStartupScript(this, this.GetType(), "Key", "<script>MakeStaticHeader('" + grdInvoice.ClientID + "', 400, 950 , 40 ,true); </script>", false);
        }
         
        protected void btnAutoMatch_Click(object sender, EventArgs e)
        {
            objReconcileService = new ReconcileService();
            DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
            DataTable dtStatement = (DataTable)Session["UnMatchedStatementList"];
           // objReconcileService.ReconcileByExactAmount((DataTable)Session["UnMatchedInvoiceList"], (DataTable)Session["UnMatchedStatementList"]);
            showPopUp(dtInvoice, dtStatement, false,"Amount");

           // GetUnmatchedLists();
           
            //Logic to re bind data table in grid view
            /*
            grdInvoice.DataSource = (DataTable)Session["UnMatchedInvoiceList"] ;
            grdInvoice.DataBind();
            grdInvoice.Columns[0].Visible = false;

            grdStatement.DataSource = (DataTable)Session["UnMatchedStatementList"];
            grdStatement.DataBind();
            grdStatement.Columns[0].Visible = false;
             */
        }

        protected void btnManualMatch_Click(object sender, EventArgs e)
        {
            showPopUp(null, null, true,"Manual");
            
            //DataTable dtMatchList = new DataTable();
            //dtMatchList.Columns.Add("invoice_unique_id", typeof(System.Int32));
            //dtMatchList.Columns.Add("statement_unique_id", typeof(System.Int32));
            //dtMatchList.Columns.Add("invoice_number", typeof(System.String));
            //dtMatchList.Columns.Add("date", typeof(System.DateTime));
            //dtMatchList.Columns.Add("remitter_id", typeof(System.String));
            //dtMatchList.Columns.Add("amount", typeof(System.Double));
            //dtMatchList.Columns.Add("ref_no_or_cheque_no", typeof(System.String));
            //dtMatchList.Columns.Add("value_date", typeof(System.DateTime));
            //dtMatchList.Columns.Add("narration1", typeof(System.String));
            //dtMatchList.Columns.Add("statement_amount", typeof(System.Double));          

            //DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
            //DataTable dtStatement = (DataTable)Session["UnMatchedStatementList"];
            //int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;

            //foreach (GridViewRow invoiceRow in grdInvoice.Rows)
            //{
            //    invoiceRowNumber++;
            //    System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
            //    //CheckBox chkSelect = ((CheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
            //    if (chkSelect.Checked)
            //    {
            //        invoiceAdded++;

            //        Literal ltlInvoiceUniqueID = ((Literal)invoiceRow.Cells[0].FindControl("ltlInvoiceUniqueID"));

            //        DataRow dr = dtMatchList.NewRow();
            //        dr[0] = ltlInvoiceUniqueID.Text;
            //        dr[2] = invoiceRow.Cells[1].Text;
            //        dr[3] = invoiceRow.Cells[2].Text;
            //        dr[4] = invoiceRow.Cells[3].Text;
            //        dr[5] = invoiceRow.Cells[4].Text;
            //        dtMatchList.Rows.Add(dr);

            //        dtInvoice.Rows[invoiceRowNumber - invoiceAdded].Delete();
            //        dtInvoice.Rows[invoiceRowNumber - invoiceAdded].AcceptChanges();
            //    }
            //}

            //foreach (GridViewRow statementRow in grdStatement.Rows)
            //{
            //    statementRowNumber++;
            //    System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)statementRow.Cells[0].FindControl("chkSelect"));
            //    //CheckBox chkSelect = ((CheckBox)statementRow.Cells[0].FindControl("chkSelect"));
            //    if (chkSelect.Checked)
            //    {
            //        statementAdded++;

            //        Literal ltlStatementUniqueID = ((Literal)statementRow.Cells[0].FindControl("ltlStatementUniqueID"));

            //        if (statementAdded <= invoiceAdded)
            //        {
            //            DataRow dr = dtMatchList.Rows[statementAdded - 1];
            //            dr[1] = ltlStatementUniqueID.Text;
            //            dr[6] = statementRow.Cells[1].Text;
            //            dr[7] = statementRow.Cells[2].Text;
            //            dr[8] = statementRow.Cells[3].Text;
            //            dr[9] = statementRow.Cells[4].Text;
            //        }
            //        else
            //        {
            //            DataRow dr = dtMatchList.NewRow();
            //            dr[1] = ltlStatementUniqueID.Text;
            //            dr[6] = statementRow.Cells[1].Text;
            //            dr[7] = statementRow.Cells[2].Text;
            //            dr[8] = statementRow.Cells[3].Text;
            //            dr[9] = statementRow.Cells[4].Text;
            //            dtMatchList.Rows.Add(dr);
            //        }

            //        dtStatement.Rows[statementRowNumber - statementAdded].Delete();
            //        dtStatement.Rows[statementRowNumber - statementAdded].AcceptChanges();
            //    }
            //}

            //grdMatchList.DataSource = dtMatchList;
            //grdMatchList.DataBind();
            
            //Session["UnMatchedInvoiceList"] = dtInvoice;
            //grdInvoice.DataSource = dtInvoice;
            //grdInvoice.DataBind();

            //Session["UnMatchedStatementList"] = dtStatement;
            //grdStatement.DataSource = dtStatement;
            //grdStatement.DataBind();

            //ManualMatchConfirmationPopup.Show();
        }

        protected void btnConfirmMatches_Click(object sender, EventArgs e)
        {
            DBFactory db = new DBFactory();

            if (Session["MatchType"] != null && Session["MatchType"].ToString().Trim() == "Manual")
            {
                DataTable dtMatchList = new DataTable();
                dtMatchList.Columns.Add("invoice_unique_id", typeof(System.Int32));
                dtMatchList.Columns.Add("statement_unique_id", typeof(System.Int32));
                dtMatchList.Columns.Add("invoice_number", typeof(System.String));
                dtMatchList.Columns.Add("date", typeof(System.DateTime));
                dtMatchList.Columns.Add("remitter_id", typeof(System.String));
                dtMatchList.Columns.Add("amount", typeof(System.Double));
                dtMatchList.Columns.Add("ref_no_or_cheque_no", typeof(System.String));
                dtMatchList.Columns.Add("value_date", typeof(System.DateTime));
                dtMatchList.Columns.Add("narration1", typeof(System.String));
                dtMatchList.Columns.Add("statement_amount", typeof(System.Double));

                foreach (GridViewRow invoiceRow in grdMatchList.Rows)
                {
                    Literal ltlInvoiceUniqueID = ((Literal)invoiceRow.Cells[0].FindControl("ltlInvoiceUniqueID"));
                    if (string.IsNullOrEmpty(ltlInvoiceUniqueID.Text))
                    {
                        break;
                    }

                    foreach (GridViewRow statementRow in grdMatchList.Rows)
                    {
                        Literal ltlStatementUniqueID = ((Literal)statementRow.Cells[1].FindControl("ltlStatementUniqueID"));
                        if (string.IsNullOrEmpty(ltlStatementUniqueID.Text))
                        {
                            break;
                        }

                        DataRow dr = dtMatchList.NewRow();
                        dr[0] = ltlInvoiceUniqueID.Text;
                        dr[2] = invoiceRow.Cells[1].Text;
                        dr[3] = invoiceRow.Cells[2].Text;
                        dr[4] = invoiceRow.Cells[3].Text;
                        dr[5] = invoiceRow.Cells[4].Text;
                        dr[1] = ltlStatementUniqueID.Text;
                        dr[6] = statementRow.Cells[5].Text;
                        dr[7] = statementRow.Cells[6].Text;
                        dr[8] = statementRow.Cells[7].Text;
                        dr[9] = statementRow.Cells[8].Text;
                        dtMatchList.Rows.Add(dr);
                    }
                }

                
                db.MatchInvoices(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, dtMatchList,"Manual");

                //get fresh list after database update and update UI
                GetUnmatchedLists();

                //Clear matched records from the UI
                grdMatchList.DataSource = null;
                grdMatchList.DataBind();

                ManualMatchConfirmationPopup.Hide();
            }
            else if (Session["MatchType"] != null && Session["MatchType"].ToString().Trim() == "Amount")
            {
                db.MatchInvoices(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, (DataTable)Session["AutoAmountMatchConfirmPopUp"],"Amount");

                //get fresh list after database update and update UI
                GetUnmatchedLists();

                //Clear matched records from the UI
                grdMatchList.DataSource = null;
                grdMatchList.DataBind();

                ManualMatchConfirmationPopup.Hide();
                
            }
            else if (Session["MatchType"] != null && Session["MatchType"].ToString().Trim() == "Amount&Ref")
            {
                db.MatchInvoices(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, (DataTable)Session["AutoAmountMatchConfirmPopUp"], "Amount&Ref");

                //get fresh list after database update and update UI
                GetUnmatchedLists();

                //Clear matched records from the UI
                grdMatchList.DataSource = null;
                grdMatchList.DataBind();

                ManualMatchConfirmationPopup.Hide();

            }
            else if (Session["MatchType"] != null && Session["MatchType"].ToString().Trim() == "Discount")
            {
                db.MatchInvoices(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, (DataTable)Session["AutoAmountMatchConfirmPopUp"], "Discount");

                //get fresh list after database update and update UI
                GetUnmatchedLists();

                //Clear matched records from the UI
                grdMatchList.DataSource = null;
                grdMatchList.DataBind();

                ManualMatchConfirmationPopup.Hide();

            }
            else if (Session["MatchType"] != null && Session["MatchType"].ToString().Trim() == "Penalty")
            {
                db.MatchInvoices(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, (DataTable)Session["AutoAmountMatchConfirmPopUp"], "Penalty");

                //get fresh list after database update and update UI
                GetUnmatchedLists();

                //Clear matched records from the UI
                grdMatchList.DataSource = null;
                grdMatchList.DataBind();

                ManualMatchConfirmationPopup.Hide();

            }
        }

        protected void btnCancelMatches_Click(object sender, EventArgs e)
        {
            //get fresh list after database update and update UI
            GetUnmatchedLists();

            //Clear matched records from the UI
            grdMatchList.DataSource = null;
            grdMatchList.DataBind();

            ManualMatchConfirmationPopup.Hide();
        }

        protected void btnAutoByRef_Click(object sender, EventArgs e)
        {
            objReconcileService = new ReconcileService();
            DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
            DataTable dtStatement = (DataTable)Session["UnMatchedStatementList"];
            //objReconcileService.ReconcileByAmountAndRef((DataTable)Session["UnMatchedInvoiceList"], (DataTable)Session["UnMatchedStatementList"]);
            showPopUp(dtInvoice, dtStatement, false, "Amount&Ref");
            //GetUnmatchedLists();
        }

        protected void btnAutoByDiscount_Click(object sender, EventArgs e)
        {
            objReconcileService = new ReconcileService();
            DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
            DataTable dtStatement = (DataTable)Session["UnMatchedStatementList"];
            //objReconcileService.ReconcileByDiscount((DataTable)Session["UnMatchedInvoiceList"], (DataTable)Session["UnMatchedStatementList"]);
            showPopUp(dtInvoice, dtStatement, false, "Discount");
            //GetUnmatchedLists();
        }

        protected void btnAutoByPenalty_Click(object sender, EventArgs e)
        {
            objReconcileService = new ReconcileService();
            DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
            DataTable dtStatement = (DataTable)Session["UnMatchedStatementList"];
            //objReconcileService.ReconcileByPenalty((DataTable)Session["UnMatchedInvoiceList"], (DataTable)Session["UnMatchedStatementList"]);
            showPopUp(dtInvoice, dtStatement, false, "Penalty");
            //GetUnmatchedLists();
        }

        protected void btnSendToRemitter_Click(object sender, EventArgs e)
        {
            DataTable dtRemitterList = new DataTable();
            dtRemitterList.Columns.Add("invoice_unique_id", typeof(System.Int32));
            dtRemitterList.Columns.Add("invoice_number", typeof(System.String));
            dtRemitterList.Columns.Add("date", typeof(System.DateTime));
            dtRemitterList.Columns.Add("remitter_id", typeof(System.String));
            dtRemitterList.Columns.Add("amount", typeof(System.Double));

            DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
            int invoiceRowNumber = 0, invoiceAdded = 0;

            foreach (GridViewRow invoiceRow in grdInvoice.Rows)
            {
                invoiceRowNumber++;
                System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
                //CheckBox chkSelect = ((CheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
                if (chkSelect.Checked)
                {
                    invoiceAdded++;

                    Literal ltlInvoiceUniqueID = ((Literal)invoiceRow.Cells[0].FindControl("ltlInvoiceUniqueID"));

                    DataRow dr = dtRemitterList.NewRow();
                    dr[0] = ltlInvoiceUniqueID.Text;
                    dr[1] = invoiceRow.Cells[1].Text;
                    dr[2] = invoiceRow.Cells[2].Text.Substring(3, 2) + "/" + invoiceRow.Cells[2].Text.Substring(0, 2) + "/" + invoiceRow.Cells[2].Text.Substring(6, 4);
                    dr[3] = invoiceRow.Cells[3].Text;
                    dr[4] = invoiceRow.Cells[4].Text;
                    dtRemitterList.Rows.Add(dr);

                    dtInvoice.Rows[invoiceRowNumber - invoiceAdded].Delete();
                    dtInvoice.Rows[invoiceRowNumber - invoiceAdded].AcceptChanges();
                }
            }

            grdRemitter.DataSource = dtRemitterList;
            grdRemitter.DataBind();

            //DBFactory db = new DBFactory();
            //db.SendInvoicesToRemitter(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, dtRemitterList);

            Session["UnMatchedInvoiceList"] = dtInvoice;
            grdInvoice.DataSource = dtInvoice;
            grdInvoice.DataBind();

            RemitterConfirmationPopup.Show();
        }

        private void GetUnmatchedLists()
        {
            db = new DBFactory();
            DataTable dtInvoice = db.GetUnmatchedInvoices(((UserVO)Session["CurrentUserVO"]).customerId,ddlRemitter.SelectedValue.ToString().Trim());
            Session["UnMatchedInvoiceList"] = dtInvoice;
            grdInvoice.DataSource = dtInvoice;
            grdInvoice.DataBind();

            DataTable dtStatement = db.GetUnmatchedStatements(((UserVO)Session["CurrentUserVO"]).customerId);
            Session["UnMatchedStatementList"] = dtStatement;
            grdStatement.DataSource = dtStatement;
            grdStatement.DataBind();
        }

 
		private void FillRemitterForMatching()
        {
            db = new DBFactory();
            DataTable dtRemitter = db.GetRemitterIdForMatchingCriteria(((UserVO)Session["CurrentUserVO"]).customerId);

            if (dtRemitter != null && dtRemitter.Rows.Count > 0)
            {
                for (int i = 0; i < dtRemitter.Rows.Count; i++)
                {
                    ddlRemitter.Items.Add(dtRemitter.Rows[i].ItemArray[0].ToString().Trim() + " - " + dtRemitter.Rows[i].ItemArray[1].ToString().Trim());
                    ddlRemitter.Items[i + 1].Value = (dtRemitter.Rows[i].ItemArray[0].ToString().Trim());
                }
            }
            //else
            //{
                           
            //}
        }

		protected void ddlRemitter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlRemitter.SelectedValue != "0")
            {
                GetUnmatchedLists();
            }
            else
            {
                //Clear matched records from the UI
                grdInvoice.DataSource = null;
                grdInvoice.DataBind();

                //Clear matched records from the UI
                grdStatement.DataSource = null;
                grdStatement.DataBind();
            }
        }

        private void showPopUp(DataTable dtInvoiceUnMatch, DataTable dtStatementUnMatch, bool isManual,string matchType)
        {
            
            bool isMatched = false;
            DataTable dtMatchList = new DataTable();
            dtMatchList.Columns.Add("invoice_unique_id", typeof(System.Int32));
            dtMatchList.Columns.Add("statement_unique_id", typeof(System.Int32));
            dtMatchList.Columns.Add("invoice_number", typeof(System.String));
            dtMatchList.Columns.Add("date", typeof(System.DateTime));
            dtMatchList.Columns.Add("remitter_id", typeof(System.String));
            dtMatchList.Columns.Add("amount", typeof(System.Double));
            dtMatchList.Columns.Add("ref_no_or_cheque_no", typeof(System.String));
            dtMatchList.Columns.Add("value_date", typeof(System.DateTime));
            dtMatchList.Columns.Add("narration1", typeof(System.String));
            dtMatchList.Columns.Add("statement_amount", typeof(System.Double));


            if (matchType == "Manual")
            {               
                DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];
                DataTable dtStatement = (DataTable)Session["UnMatchedStatementList"];
                int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;

                foreach (GridViewRow invoiceRow in grdInvoice.Rows)
                {
                    invoiceRowNumber++;
                    System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
                    //CheckBox chkSelect = ((CheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
                    if (chkSelect.Checked)
                    {
                        invoiceAdded++;

                        Literal ltlInvoiceUniqueID = ((Literal)invoiceRow.Cells[0].FindControl("ltlInvoiceUniqueID"));

                        DataRow dr = dtMatchList.NewRow();
                        dr[0] = ltlInvoiceUniqueID.Text;
                        dr[2] = invoiceRow.Cells[1].Text;
                        dr[3] = invoiceRow.Cells[2].Text;
                        dr[4] = invoiceRow.Cells[3].Text;
                        dr[5] = invoiceRow.Cells[4].Text;
                        dtMatchList.Rows.Add(dr);

                        dtInvoice.Rows[invoiceRowNumber - invoiceAdded].Delete();
                        dtInvoice.Rows[invoiceRowNumber - invoiceAdded].AcceptChanges();
                    }
                }

                foreach (GridViewRow statementRow in grdStatement.Rows)
                {
                    statementRowNumber++;
                    System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)statementRow.Cells[0].FindControl("chkSelect"));
                    //CheckBox chkSelect = ((CheckBox)statementRow.Cells[0].FindControl("chkSelect"));
                    if (chkSelect.Checked)
                    {
                        statementAdded++;

                        Literal ltlStatementUniqueID = ((Literal)statementRow.Cells[0].FindControl("ltlStatementUniqueID"));

                        if (statementAdded <= invoiceAdded)
                        {
                            DataRow dr = dtMatchList.Rows[statementAdded - 1];
                            dr[1] = ltlStatementUniqueID.Text;
                            dr[6] = statementRow.Cells[1].Text;
                            dr[7] = statementRow.Cells[2].Text;
                            dr[8] = statementRow.Cells[3].Text;
                            dr[9] = statementRow.Cells[4].Text;
                        }
                        else
                        {
                            DataRow dr = dtMatchList.NewRow();
                            dr[1] = ltlStatementUniqueID.Text;
                            dr[6] = statementRow.Cells[1].Text;
                            dr[7] = statementRow.Cells[2].Text;
                            dr[8] = statementRow.Cells[3].Text;
                            dr[9] = statementRow.Cells[4].Text;
                            dtMatchList.Rows.Add(dr);
                        }

                        dtStatement.Rows[statementRowNumber - statementAdded].Delete();
                        dtStatement.Rows[statementRowNumber - statementAdded].AcceptChanges();
                    }
                }

                if (dtMatchList.Rows.Count > 0)
                {
                    Session["MatchType"] = matchType;
                    grdMatchList.DataSource = dtMatchList;
                    grdMatchList.DataBind();
                }
                else
                {
                    grdMatchList.DataSource = null;
                    grdMatchList.DataBind();
                }

                Session["UnMatchedInvoiceList"] = dtInvoice;
                grdInvoice.DataSource = dtInvoice;
                grdInvoice.DataBind();

                Session["UnMatchedStatementList"] = dtStatement;
                grdStatement.DataSource = dtStatement;
                grdStatement.DataBind();

                ManualMatchConfirmationPopup.Show();
            }
            else if(matchType == "Amount")
            {
                int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;
                for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                {
                    double invoiceAmt;
                    invoiceRowNumber++;
                    //check for previous row matched or not.
                    if (!isMatched)
                    {
                        //if not matched then continue
                         invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                         //current count
                         invoiceRowNumber = invCount;
                    }
                    else
                    {
                        //if matched then start from "0".
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[0]["amount"]);
                        //reset  count to "0"
                        invoiceRowNumber = 0;
                    }

                    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                    {
                        statementRowNumber++;
                        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);

                        if (invoiceAmt == stmntAmt)
                        {
                            invoiceAdded++;
                            statementAdded++;
                            //matchType = "Amount";
                            DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invoiceRowNumber];//dtInvoiceUnMatch.Rows[invCount];
                            DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                            //insertMatchedInvoice(matchedInvoiceRow, matchedStmtRow);

                            //SELECT invoice_unique_id, remitter_id, invoice_number, date, currency, po_ref, amount + service_tax + vat + cess + sales_tax + tax1 + tax2 + tax3 - discount as amount, invoic_status, is_partial FROM pro_invoice WHERE customer_id = '" + CustomerID + "' AND remitter_id = '" + RemitterId + "' AND invoic_status IN ('N', 'U', 'P', 'R')
                            DataRow dr = dtMatchList.NewRow();
                            dr[0] = matchedInvoiceRow["invoice_unique_id"].ToString();
                            dr[2] = matchedInvoiceRow[2].ToString();
                            dr[3] = DateTime.Parse(matchedInvoiceRow[3].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd"));
                            dr[4] = matchedInvoiceRow[1].ToString(); 
                            dr[5] = Double.Parse(matchedInvoiceRow[6].ToString());

                            //SELECT statement_unique_id, bank_id, value_date, ref_no_or_cheque_no, narration1, amount FROM pro_statement WHERE customer_id = '" + CustomerID + "' AND statement_status IN ('N', 'U', 'P', 'R')
                            dr[1] = matchedStmtRow["statement_unique_id"].ToString();// ltlStatementUniqueID.Text;
                            dr[6] = matchedStmtRow[3].ToString(); //statementRow.Cells[1].Text;
                            dr[7] = DateTime.Parse(matchedStmtRow[2].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd")); //statementRow.Cells[2].Text;
                            dr[8] = matchedStmtRow[4].ToString();// statementRow.Cells[3].Text;
                            dr[9] = Double.Parse(matchedStmtRow[5].ToString()); //statementRow.Cells[4].Text;
                            dtMatchList.Rows.Add(dr);

                            //dtInvoiceUnMatch.Rows[invoiceRowNumber - invoiceAdded].Delete();
                            //dtInvoiceUnMatch.Rows[invoiceRowNumber - invoiceAdded].AcceptChanges();

                            //dtStatementUnMatch.Rows[statementRowNumber - statementAdded].Delete();
                            //dtStatementUnMatch.Rows[statementRowNumber - statementAdded].AcceptChanges();

                            dtInvoiceUnMatch.Rows[invoiceRowNumber].Delete();
                            dtInvoiceUnMatch.Rows[invoiceRowNumber].AcceptChanges();

                            dtStatementUnMatch.Rows[stmCount].Delete();
                            dtStatementUnMatch.Rows[stmCount].AcceptChanges();
                            //if matched then make flag true and invcount reset to 0 and break current for loop
                            isMatched = true;
                            invCount = -1;
                            break;
                        }
                        //if not matched then make flag false
                        isMatched = false;
                    }
                }


                if (dtMatchList.Rows.Count > 0)
                {
                    Session["AutoAmountMatchConfirmPopUp"] = dtMatchList;
                    Session["MatchType"] = matchType;
                    grdMatchList.DataSource = dtMatchList;
                    grdMatchList.DataBind();
                }
                else
                {
                    Session["AutoAmountMatchConfirmPopUp"] = null;
                    grdMatchList.DataSource = null;
                    grdMatchList.DataBind();
                }
               

                Session["UnMatchedInvoiceList"] = dtInvoiceUnMatch;
                grdInvoice.DataSource = dtInvoiceUnMatch;
                grdInvoice.DataBind();

                Session["UnMatchedStatementList"] = dtStatementUnMatch;
                grdStatement.DataSource = dtStatementUnMatch;
                grdStatement.DataBind();

                ManualMatchConfirmationPopup.Show();

            }

            else if (matchType == "Amount&Ref")
            {
                //for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                //{
                //    double invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                //    String InvoiceNumber = (dtInvoiceUnMatch.Rows[invCount]["invoice_number"]).ToString();
                //    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                //    {
                //        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);
                //        String stmtInvoiceNumber = (dtStatementUnMatch.Rows[stmCount]["ref_no_or_cheque_no"]).ToString();
                //        if (invoiceAmt == stmntAmt && (InvoiceNumber == stmtInvoiceNumber))
                //        {
                //            matchType = "Amount&Ref";
                //            DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invCount];
                //            DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                            
                //        }
                //    }
                //}

                int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;
                for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                {
                    double invoiceAmt;
                    String InvoiceNumber;
                    invoiceRowNumber++;
                    //check for previous row matched or not.
                    if (!isMatched)
                    {
                        //if not matched then continue
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                        InvoiceNumber = (dtInvoiceUnMatch.Rows[invCount]["invoice_number"]).ToString();
                        //current count
                        invoiceRowNumber = invCount;
                    }
                    else
                    {
                        //if matched then start from "0".
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[0]["amount"]);
                        InvoiceNumber = (dtInvoiceUnMatch.Rows[0]["invoice_number"]).ToString();
                        //reset  count to "0"
                        invoiceRowNumber = 0;
                    }

                    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                    {
                        statementRowNumber++;
                        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);
                        String stmtInvoiceNumber = (dtStatementUnMatch.Rows[stmCount]["ref_no_or_cheque_no"]).ToString();

                        if (invoiceAmt == stmntAmt && (InvoiceNumber == stmtInvoiceNumber))
                        {
                            invoiceAdded++;
                            statementAdded++;
                            //matchType = "Amount";
                            DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invoiceRowNumber];//dtInvoiceUnMatch.Rows[invCount];
                            DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                            //insertMatchedInvoice(matchedInvoiceRow, matchedStmtRow);

                            //SELECT invoice_unique_id, remitter_id, invoice_number, date, currency, po_ref, amount + service_tax + vat + cess + sales_tax + tax1 + tax2 + tax3 - discount as amount, invoic_status, is_partial FROM pro_invoice WHERE customer_id = '" + CustomerID + "' AND remitter_id = '" + RemitterId + "' AND invoic_status IN ('N', 'U', 'P', 'R')
                            DataRow dr = dtMatchList.NewRow();
                            dr[0] = matchedInvoiceRow["invoice_unique_id"].ToString();
                            dr[2] = matchedInvoiceRow[2].ToString();
                            dr[3] = DateTime.Parse(matchedInvoiceRow[3].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd"));
                            dr[4] = matchedInvoiceRow[1].ToString();
                            dr[5] = Double.Parse(matchedInvoiceRow[6].ToString());

                            //SELECT statement_unique_id, bank_id, value_date, ref_no_or_cheque_no, narration1, amount FROM pro_statement WHERE customer_id = '" + CustomerID + "' AND statement_status IN ('N', 'U', 'P', 'R')
                            dr[1] = matchedStmtRow["statement_unique_id"].ToString();// ltlStatementUniqueID.Text;
                            dr[6] = matchedStmtRow[3].ToString(); //statementRow.Cells[1].Text;
                            dr[7] = DateTime.Parse(matchedStmtRow[2].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd")); //statementRow.Cells[2].Text;
                            dr[8] = matchedStmtRow[4].ToString();// statementRow.Cells[3].Text;
                            dr[9] = Double.Parse(matchedStmtRow[5].ToString()); //statementRow.Cells[4].Text;
                            dtMatchList.Rows.Add(dr);

                            dtInvoiceUnMatch.Rows[invoiceRowNumber].Delete();
                            dtInvoiceUnMatch.Rows[invoiceRowNumber].AcceptChanges();

                            dtStatementUnMatch.Rows[stmCount].Delete();
                            dtStatementUnMatch.Rows[stmCount].AcceptChanges();
                            //if matched then make flag true and invcount reset to 0 and break current for loop
                            isMatched = true;
                            invCount = -1;
                            break;
                        }
                        //if not matched then make flag false
                        isMatched = false;
                    }
                }

                if (dtMatchList.Rows.Count > 0)
                {
                    Session["AutoAmountMatchConfirmPopUp"] = dtMatchList;
                    Session["MatchType"] = matchType;
                    grdMatchList.DataSource = dtMatchList;
                    grdMatchList.DataBind();
                }
                else
                {
                    Session["AutoAmountMatchConfirmPopUp"] = null;
                    grdMatchList.DataSource = null;
                    grdMatchList.DataBind();
                }

                Session["UnMatchedInvoiceList"] = dtInvoiceUnMatch;
                grdInvoice.DataSource = dtInvoiceUnMatch;
                grdInvoice.DataBind();

                Session["UnMatchedStatementList"] = dtStatementUnMatch;
                grdStatement.DataSource = dtStatementUnMatch;
                grdStatement.DataBind();

                ManualMatchConfirmationPopup.Show();
            }
            else if (matchType == "Discount")
            {
                //for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                //{
                //    double invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                //    string remId = Convert.ToString(dtInvoiceUnMatch.Rows[invCount]["remitter_id"]);
                //    DateTime invoiceDate = Convert.ToDateTime(dtInvoiceUnMatch.Rows[invCount]["date"]);

                //    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                //    {
                //        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);
                //        DateTime statementDate = Convert.ToDateTime(dtStatementUnMatch.Rows[stmCount]["value_date"]); ;

                //        double discountPerc = 0.00;
                //        double discountAmount = 0.00;

                //        objReconcileService = new ReconcileService();
                //        discountPerc = objReconcileService.getDiscountDetails(((UserVO)Session["CurrentUserVO"]).customerId,remId,);
                        
                //        if (discountPerc > 0.0)
                //        {
                //            discountAmount = invoiceAmt * (discountPerc / 100);
                //            if (((invoiceAmt - (discountAmount)) == stmntAmt))
                //            {
                //                matchType = "Discount";
                //                DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invCount];
                //                DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                //            }
                //        }
                //    }
                //}


                int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;
                for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                {
                    double invoiceAmt;
                    string remId;
                    DateTime invoiceDate;
                    invoiceRowNumber++;
                    //check for previous row matched or not.
                    if (!isMatched)
                    {
                        //if not matched then continue
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                        remId = Convert.ToString(dtInvoiceUnMatch.Rows[invCount]["remitter_id"]);
                        invoiceDate = Convert.ToDateTime(dtInvoiceUnMatch.Rows[invCount]["date"]);
                        //current count
                        invoiceRowNumber = invCount;
                    }
                    else
                    {
                        //if matched then start from "0".
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[0]["amount"]);
                        remId = Convert.ToString(dtInvoiceUnMatch.Rows[0]["remitter_id"]);
                        invoiceDate = Convert.ToDateTime(dtInvoiceUnMatch.Rows[0]["date"]);
                        //reset  count to "0"
                        invoiceRowNumber = 0;
                    }

                    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                    {
                        statementRowNumber++;
                        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);
                        DateTime statementDate = Convert.ToDateTime(dtStatementUnMatch.Rows[stmCount]["value_date"]); ;

                        double discountPerc = 0.00;
                        double discountAmount = 0.00;

                        objReconcileService = new ReconcileService();
                        discountPerc = objReconcileService.getDiscountDetails(((UserVO)Session["CurrentUserVO"]).customerId,remId,invoiceDate,statementDate);

                        if (discountPerc > 0.0)
                        {
                            discountAmount = invoiceAmt * (discountPerc / 100);
                            if (((invoiceAmt - (discountAmount)) == stmntAmt))
                            {
                                invoiceAdded++;
                            statementAdded++;
                            //matchType = "Amount";
                            DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invoiceRowNumber];//dtInvoiceUnMatch.Rows[invCount];
                            DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                            //insertMatchedInvoice(matchedInvoiceRow, matchedStmtRow);

                            //SELECT invoice_unique_id, remitter_id, invoice_number, date, currency, po_ref, amount + service_tax + vat + cess + sales_tax + tax1 + tax2 + tax3 - discount as amount, invoic_status, is_partial FROM pro_invoice WHERE customer_id = '" + CustomerID + "' AND remitter_id = '" + RemitterId + "' AND invoic_status IN ('N', 'U', 'P', 'R')
                            DataRow dr = dtMatchList.NewRow();
                            dr[0] = matchedInvoiceRow["invoice_unique_id"].ToString();
                            dr[2] = matchedInvoiceRow[2].ToString();
                            dr[3] = DateTime.Parse(matchedInvoiceRow[3].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd"));
                            dr[4] = matchedInvoiceRow[1].ToString();
                            dr[5] = Double.Parse(matchedInvoiceRow[6].ToString());

                            //SELECT statement_unique_id, bank_id, value_date, ref_no_or_cheque_no, narration1, amount FROM pro_statement WHERE customer_id = '" + CustomerID + "' AND statement_status IN ('N', 'U', 'P', 'R')
                            dr[1] = matchedStmtRow["statement_unique_id"].ToString();// ltlStatementUniqueID.Text;
                            dr[6] = matchedStmtRow[3].ToString(); //statementRow.Cells[1].Text;
                            dr[7] = DateTime.Parse(matchedStmtRow[2].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd")); //statementRow.Cells[2].Text;
                            dr[8] = matchedStmtRow[4].ToString();// statementRow.Cells[3].Text;
                            dr[9] = Double.Parse(matchedStmtRow[5].ToString()); //statementRow.Cells[4].Text;
                            dtMatchList.Rows.Add(dr);

                            dtInvoiceUnMatch.Rows[invoiceRowNumber].Delete();
                            dtInvoiceUnMatch.Rows[invoiceRowNumber].AcceptChanges();

                            dtStatementUnMatch.Rows[stmCount].Delete();
                            dtStatementUnMatch.Rows[stmCount].AcceptChanges();
                            //if matched then make flag true and invcount reset to 0 and break current for loop
                            isMatched = true;
                            invCount = -1;
                            break;
                            }
                            //if not matched then make flag false
                            isMatched = false;
                        } 
                        //if not matched then make flag false
                        isMatched = false;
                    }
                }

                if (dtMatchList.Rows.Count > 0)
                {
                    Session["AutoAmountMatchConfirmPopUp"] = dtMatchList;
                    Session["MatchType"] = matchType;
                    grdMatchList.DataSource = dtMatchList;
                    grdMatchList.DataBind();
                }
                else
                {
                    Session["AutoAmountMatchConfirmPopUp"] = null;
                    grdMatchList.DataSource = null;
                    grdMatchList.DataBind();
                }

                Session["UnMatchedInvoiceList"] = dtInvoiceUnMatch;
                grdInvoice.DataSource = dtInvoiceUnMatch;
                grdInvoice.DataBind();

                Session["UnMatchedStatementList"] = dtStatementUnMatch;
                grdStatement.DataSource = dtStatementUnMatch;
                grdStatement.DataBind();

                ManualMatchConfirmationPopup.Show();
            }
            else if (matchType == "Penalty")
            {
                //for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                //{
                //    double invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                //    string remId = Convert.ToString(dtInvoiceUnMatch.Rows[invCount]["remitter_id"]);
                //    DateTime invoiceDate = Convert.ToDateTime(dtInvoiceUnMatch.Rows[invCount]["date"]);

                //    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                //    {
                //        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);
                //        DateTime statementDate = Convert.ToDateTime(dtStatementUnMatch.Rows[stmCount]["value_date"]); ;
                //        double penaltyPerc = 0.00;
                //        double penaltyAmount = 0.00;
                        
                //        if (penaltyPerc > 0.0)
                //        {

                //            penaltyAmount = invoiceAmt * (penaltyPerc / 100);
                //            if (((invoiceAmt + (penaltyAmount)) == stmntAmt))
                //            {
                //                matchType = "Penalty";
                //                DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invCount];
                //                DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                //                insertMatchedInvoice(matchedInvoiceRow, matchedStmtRow);

                //            }
                //        }
                //    }
                //}

                int invoiceRowNumber = 0, statementRowNumber = 0, invoiceAdded = 0, statementAdded = 0;
                for (int invCount = 0; invCount < dtInvoiceUnMatch.Rows.Count; invCount++)
                {
                    double invoiceAmt;
                    string remId;
                    DateTime invoiceDate;
                    invoiceRowNumber++;
                    //check for previous row matched or not.
                    if (!isMatched)
                    {
                        //if not matched then continue
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[invCount]["amount"]);
                        remId = Convert.ToString(dtInvoiceUnMatch.Rows[invCount]["remitter_id"]);
                        invoiceDate = Convert.ToDateTime(dtInvoiceUnMatch.Rows[invCount]["date"]);
                        //current count
                        invoiceRowNumber = invCount;
                    }
                    else
                    {
                        //if matched then start from "0".
                        invoiceAmt = Convert.ToDouble(dtInvoiceUnMatch.Rows[0]["amount"]);
                        remId = Convert.ToString(dtInvoiceUnMatch.Rows[0]["remitter_id"]);
                        invoiceDate = Convert.ToDateTime(dtInvoiceUnMatch.Rows[0]["date"]);
                        //reset  count to "0"
                        invoiceRowNumber = 0;
                    }

                    for (int stmCount = 0; stmCount < dtStatementUnMatch.Rows.Count; stmCount++)
                    {
                        statementRowNumber++;
                        double stmntAmt = Convert.ToDouble(dtStatementUnMatch.Rows[stmCount]["amount"]);
                        DateTime statementDate = Convert.ToDateTime(dtStatementUnMatch.Rows[stmCount]["value_date"]); ;
                        double penaltyPerc = 0.00;
                        double penaltyAmount = 0.00;

                        objReconcileService = new ReconcileService();
                        penaltyPerc = objReconcileService.getPenaltyDetails(((UserVO)Session["CurrentUserVO"]).customerId, remId, invoiceDate, statementDate);

                        if (penaltyPerc > 0.0)
                        {
                            penaltyAmount = invoiceAmt * (penaltyPerc / 100);

                            if (((invoiceAmt + (penaltyAmount)) == stmntAmt))
                            {
                                invoiceAdded++;
                                statementAdded++;
                                //matchType = "Amount";
                                DataRow matchedInvoiceRow = dtInvoiceUnMatch.Rows[invoiceRowNumber];//dtInvoiceUnMatch.Rows[invCount];
                                DataRow matchedStmtRow = dtStatementUnMatch.Rows[stmCount];
                                //insertMatchedInvoice(matchedInvoiceRow, matchedStmtRow);

                                //SELECT invoice_unique_id, remitter_id, invoice_number, date, currency, po_ref, amount + service_tax + vat + cess + sales_tax + tax1 + tax2 + tax3 - discount as amount, invoic_status, is_partial FROM pro_invoice WHERE customer_id = '" + CustomerID + "' AND remitter_id = '" + RemitterId + "' AND invoic_status IN ('N', 'U', 'P', 'R')
                                DataRow dr = dtMatchList.NewRow();
                                dr[0] = matchedInvoiceRow["invoice_unique_id"].ToString();
                                dr[2] = matchedInvoiceRow[2].ToString();
                                dr[3] = DateTime.Parse(matchedInvoiceRow[3].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd"));
                                dr[4] = matchedInvoiceRow[1].ToString();
                                dr[5] = Double.Parse(matchedInvoiceRow[6].ToString());

                                //SELECT statement_unique_id, bank_id, value_date, ref_no_or_cheque_no, narration1, amount FROM pro_statement WHERE customer_id = '" + CustomerID + "' AND statement_status IN ('N', 'U', 'P', 'R')
                                dr[1] = matchedStmtRow["statement_unique_id"].ToString();// ltlStatementUniqueID.Text;
                                dr[6] = matchedStmtRow[3].ToString(); //statementRow.Cells[1].Text;
                                dr[7] = DateTime.Parse(matchedStmtRow[2].ToString()); //DateTime.Parse(System.DateTime.Now.ToString("yyyy-MM-dd")); //statementRow.Cells[2].Text;
                                dr[8] = matchedStmtRow[4].ToString();// statementRow.Cells[3].Text;
                                dr[9] = Double.Parse(matchedStmtRow[5].ToString()); //statementRow.Cells[4].Text;
                                dtMatchList.Rows.Add(dr);

                                dtInvoiceUnMatch.Rows[invoiceRowNumber].Delete();
                                dtInvoiceUnMatch.Rows[invoiceRowNumber].AcceptChanges();

                                dtStatementUnMatch.Rows[stmCount].Delete();
                                dtStatementUnMatch.Rows[stmCount].AcceptChanges();
                                //if matched then make flag true and invcount reset to 0 and break current for loop
                                isMatched = true;
                                invCount = -1;
                                break;
                            }
                            //if not matched then make flag false
                            isMatched = false;
                        }
                        //if not matched then make flag false
                        isMatched = false;
                    }
                }

                if (dtMatchList.Rows.Count > 0)
                {
                    Session["AutoAmountMatchConfirmPopUp"] = dtMatchList;
                    Session["MatchType"] = matchType;
                    grdMatchList.DataSource = dtMatchList;
                    grdMatchList.DataBind();
                }
                else
                {
                    Session["AutoAmountMatchConfirmPopUp"] = null;
                    grdMatchList.DataSource = null;
                    grdMatchList.DataBind();
                }

                Session["UnMatchedInvoiceList"] = dtInvoiceUnMatch;
                grdInvoice.DataSource = dtInvoiceUnMatch;
                grdInvoice.DataBind();

                Session["UnMatchedStatementList"] = dtStatementUnMatch;
                grdStatement.DataSource = dtStatementUnMatch;
                grdStatement.DataBind();

                ManualMatchConfirmationPopup.Show();
            }
        }

        protected void grdInvoice_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                double value = 0.00;
                if (e.Row.Cells[4].Text != "" && e.Row.Cells[4].Text != "&nbsp;")
                {
                    value = Convert.ToDouble(e.Row.Cells[4].Text);
                    e.Row.Cells[4].Text = value.ToString("#,#.00", CultureInfo.InvariantCulture);
                    e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;
                }
                else
                {
                    e.Row.Cells[4].Text = "0.00";
                }
                DateTime dt;
                if (e.Row.Cells[2].Text != "" && e.Row.Cells[2].Text != "&nbsp;")
                {
                    dt = Convert.ToDateTime(e.Row.Cells[2].Text);
                    e.Row.Cells[2].Text = dt.ToString("dd-MM-yyyy");
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Center;
                }
                else
                {
                    e.Row.Cells[2].Text = "";
                }
            }       
        }

        protected void grdStatement_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                double value = 0.00;
                if (e.Row.Cells[4].Text != "" && e.Row.Cells[4].Text != "&nbsp;")
                {
                    value = Convert.ToDouble(e.Row.Cells[4].Text);
                    e.Row.Cells[4].Text = value.ToString("#,#.00", CultureInfo.InvariantCulture);
                    e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;
                }
                else
                {
                    e.Row.Cells[4].Text = "0.00";
                }
                DateTime dt;
                if (e.Row.Cells[2].Text != "" && e.Row.Cells[2].Text != "&nbsp;")
                {
                    dt = Convert.ToDateTime(e.Row.Cells[2].Text);
                    e.Row.Cells[2].Text = dt.ToString("dd-MM-yyyy");
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Center;
                }
                else
                {
                    e.Row.Cells[2].Text = "";
                }
            }       
        }

        protected void grdMatchList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                DateTime dt;
                if (e.Row.Cells[2].Text != "" && e.Row.Cells[2].Text != "&nbsp;")
                {
                    dt = Convert.ToDateTime(e.Row.Cells[2].Text);
                    e.Row.Cells[2].Text = dt.ToString("dd-MM-yyyy");
                    e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Center;
                }
                else
                {
                    e.Row.Cells[2].Text = "";
                }
                if (e.Row.Cells[6].Text != "" && e.Row.Cells[6].Text != "&nbsp;")
                {
                    dt = Convert.ToDateTime(e.Row.Cells[6].Text);
                    e.Row.Cells[6].Text = dt.ToString("dd-MM-yyyy");
                    e.Row.Cells[6].HorizontalAlign = HorizontalAlign.Center;
                }
                else
                {
                    e.Row.Cells[6].Text = "";
                }

                double value = 0.00;
                if (e.Row.Cells[4].Text != "" && e.Row.Cells[4].Text != "&nbsp;")
                {
                    value = Convert.ToDouble(e.Row.Cells[4].Text);
                    e.Row.Cells[4].Text = value.ToString("#,#.00", CultureInfo.InvariantCulture);
                    e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;
                }
                else
                {
                    e.Row.Cells[4].Text = "0.00";
                }
                if (e.Row.Cells[8].Text != "" && e.Row.Cells[8].Text != "&nbsp;")
                {
                    value = Convert.ToDouble(e.Row.Cells[8].Text);
                    e.Row.Cells[8].Text = value.ToString("#,#.00", CultureInfo.InvariantCulture);
                    e.Row.Cells[8].HorizontalAlign = HorizontalAlign.Right;
                }
                else
                {
                    e.Row.Cells[8].Text = "0.00";
                }
               
            }       
        }

        protected void grdRemitter_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void btnConfirmRemitter_Click(object sender, EventArgs e)
        {
            DataTable dtRemitterList = new DataTable();
            dtRemitterList.Columns.Add("invoice_unique_id", typeof(System.Int32));
            dtRemitterList.Columns.Add("invoice_number", typeof(System.String));
            dtRemitterList.Columns.Add("date", typeof(System.DateTime));
            dtRemitterList.Columns.Add("remitter_id", typeof(System.String));
            dtRemitterList.Columns.Add("amount", typeof(System.Double));

            DataTable dtInvoice = (DataTable)Session["UnMatchedInvoiceList"];

            foreach (GridViewRow invoiceRow in grdRemitter.Rows)
            {
                //System.Web.UI.HtmlControls.HtmlInputCheckBox chkSelect = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)invoiceRow.Cells[0].FindControl("chkSelect"));
                Literal ltlInvoiceUniqueID = ((Literal)invoiceRow.Cells[0].FindControl("ltlInvoiceUniqueID"));

                DataRow dr = dtRemitterList.NewRow();
                dr[0] = ltlInvoiceUniqueID.Text;
                dr[1] = invoiceRow.Cells[1].Text;
                dr[2] = invoiceRow.Cells[2].Text;
                dr[3] = invoiceRow.Cells[3].Text;
                dr[4] = invoiceRow.Cells[4].Text;
                dtRemitterList.Rows.Add(dr);
            }

            DBFactory db = new DBFactory();
            db.SendInvoicesToRemitter(((UserVO)Session["CurrentUserVO"]).customerId, ((UserVO)Session["CurrentUserVO"]).userId, dtRemitterList);

            //get fresh list after database update and update UI
            GetUnmatchedLists();

            //Clear sent records from the UI
            grdRemitter.DataSource = null;
            grdRemitter.DataBind();

            RemitterConfirmationPopup.Hide();
        }

        protected void btnCancelRemitter_Click(object sender, EventArgs e)
        {
            //get fresh list after database update and update UI
            GetUnmatchedLists();

            //Clear records marked for sending from the UI
            grdRemitter.DataSource = null;
            grdRemitter.DataBind();

            RemitterConfirmationPopup.Hide();
        }
    }
}